package com.ly.utils;

import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public class ImageConvertUtils {

    static {
        nu.pattern.OpenCV.loadLocally();
    }

    public static Mat fileToMat(MultipartFile file) {
        MatOfByte matOfByte = null;
        try {
            // 获取文件的字节数据
            byte[] data = file.getBytes();
            // IMREAD_COLOR 表示加载彩色图像
            matOfByte = new MatOfByte(data);
            Mat image = Imgcodecs.imdecode(matOfByte, Imgcodecs.IMREAD_COLOR);
            return image;
        } catch (IOException e) {
            throw new RuntimeException("转换错误");
        }finally {
            if (matOfByte != null) {
                matOfByte.release();
            }
        }
    }

    /**
     * 将Mat对象转换为JPEG格式的字节数组。
     * @param mat OpenCV的Mat对象
     * @return 包含JPEG图片数据的字节数组
     */
    public static byte[] matToByteArray(Mat mat) {
        MatOfByte matOfByte = new MatOfByte();
        Imgcodecs.imencode(".jpg", mat, matOfByte);
        return matOfByte.toArray();
    }

    public static void main(String[] args) {

        Mat greenImage = new Mat(1920,1280 , CvType.CV_8UC3, new Scalar(0, 255, 0));
        Imgcodecs.imwrite("12.png", greenImage);
    }

}
